Рак молочной железы Висконсин (диагностический) набор данных. Ряд случаев:569 Ряд признаков:30 числовые, предиктивные атрибуты и класс Атрибутивная информация: -radius- радиус (среднее расстояние от центра до точек по периметру) -texture- текстура (стандартное отклонение значений серой шкалы) -perimeter-периметр -area- область -smoothness- гладкость (локальное изменение длины радиуса) -compactness- компактность (периметр^2 / Площадь-1,0) -concavity- вогнутость (тяжесть вогнутых участков контура) -concave points- вогнутые точки (количество вогнутых участков контура) -symmetry- симметрия -fractal dimension- фрактальная размерность ("Береговое приближение" - 1) Среднее, Стандартная ошибка, а также " худший” или самый большой (среднее из трех наибольшие значения) этих признаков были вычислены для каждого изображения, в результате чего 30 функций. Например, поле 3-это средний радиус, поле 13-радиус SE, поле 23-наихудший радиус. Распределение по классам: 212 - Malignant, 357 - Benign
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
sns.set(style="ticks")
from sklearn.datasets import *
cancer= load_breast_cancer()
cancer.target[[10 , 50 , 85 ]]
list(cancer.target_names)
def make_dataframe(ds_function):
ds = ds_function()
df = pd.DataFrame(data= np.c_[ds['data'], ds['target']],
columns= list(ds['feature_names']) + ['target'])
return df
temp_df = make_dataframe(load_breast_cancer)
temp_df.head()
cancer['data'].shape
cancer['target'].shape
total_count = cancer['data'].shape[0]
print('Всего строк: {}'.format(total_count))
# Основные статистические характеристки набора данных
temp_df.describe()
temp_df.corr()
sns.pairplot(temp_df)
fig, ax = plt.subplots(figsize=(10,10))
sns.scatterplot(ax=ax, x='mean area', y='mean radius', data=temp_df)
fig, ax = plt.subplots(figsize=(10,10))
sns.scatterplot(ax=ax, x='mean area', y='mean radius', data=temp_df, hue='target')
fig, ax = plt.subplots(figsize=(10,10))
sns.distplot(temp_df['mean perimeter'])
sns.jointplot(x='mean area', y='mean fractal dimension', data=temp_df)
sns.jointplot(x='mean area', y='mean fractal dimension', data=temp_df, kind="kde")
sns.pairplot(temp_df, hue="target")
sns.boxplot(x='target', y='mean radius', data=temp_df)
fig, ax = plt.subplots(2, 1, figsize=(10,10))
sns.violinplot(ax=ax[0], x=temp_df['mean radius'])
sns.distplot(temp_df['mean radius'], ax=ax[1])
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.tree import DecisionTreeClassifier
X, y = load_breast_cancer( return_X_y= True)
X_train, X_test, y_train, y_test = train_test_split( X, y, random_state= 0 )
clf = DecisionTreeClassifier( random_state= 0)
path = clf.cost_complexity_pruning_path(X_train, y_train)
ccp_alphas, impurities = path.ccp_alphas, path.impurities
fig,ax = plt.subplots()
ax.plot(ccp_alphas[: - 1 ], impurities[:-1 ], marker= 'o', drawstyle= "steps-post")
ax.set_xlabel("effective alpha")
ax.set_ylabel("total impurity of leaves")
ax.set_title("Total Impurity vs effective alpha for training set")
clfs = []
for ccp_alpha in ccp_alphas:
clf = DecisionTreeClassifier(random_state= 0 , ccp_alpha= ccp_alpha)
clf.fit(X_train, y_train)
clfs.append(clf)
print("Number of nodes in the last tree is: {} with ccp_alpha: {}" .format(
clfs[- 1].tree_.node_count, ccp_alphas[ - 1]))
clfs = clfs[: - 1 ]
ccp_alphas = ccp_alphas[: - 1]
node_counts = [ clf.tree_.node_count for clf in clfs]
depth = [ clf.tree_.max_depth for clf in clfs]
fig, ax = plt.subplots(2 , 1 )
ax[ 0 ] .plot(ccp_alphas, node_counts, marker= 'o', drawstyle= "steps-post")
ax[ 0 ] .set_xlabel("alpha")
ax[ 0 ] .set_ylabel("number of nodes")
ax[ 0 ] .set_title("Number of nodes vs alpha")
ax[ 1].plot(ccp_alphas, depth, marker= 'o', drawstyle= "steps-post")
ax[ 1 ] .set_xlabel("alpha")
ax[ 1 ] .set_ylabel("depth of tree")
ax[ 1 ] .set_title("Depth vs alpha")
fig.tight_layout()
train_scores = [clf.score(X_train, y_train) for clf in clfs]
test_scores = [ clf.score(X_test, y_test) for clf in clfs]
fig, ax = plt.subplots()
ax.set_xlabel("alpha")
ax.set_ylabel("accuracy")
ax.set_title("Accuracy vs alpha for training and testing sets")
ax.plot(ccp_alphas, train_scores, marker= 'o', label= "train",
drawstyle= "steps-post")
ax.plot(ccp_alphas, test_scores, marker= 'o', label= "test",
drawstyle= "steps-post")
ax.legend()
plt.show()
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
from scipy.stats import spearmanr
from scipy.cluster import hierarchy
from sklearn.datasets import load_breast_cancer
from sklearn.ensemble import RandomForestClassifier
from sklearn.inspection import permutation_importance
from sklearn.model_selection import train_test_split
data = load_breast_cancer()
X, y = data.data, data.target
X_train, X_test, y_train, y_test = train_test_split( X, y, random_state= 42 )
clf = RandomForestClassifier(n_estimators= 100 , random_state= 42 )
clf.fit(X_train, y_train)
print("Accuracy on test data: {:.2f}".format(clf.score( X_test, y_test)))
import matplotlib.pyplot as plt
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 8))
corr = spearmanr( X).correlation
corr_linkage = hierarchy.ward(corr)
dendro = hierarchy.dendrogram( corr_linkage, labels= data.feature_names, ax= ax1,
leaf_rotation= 90)
dendro_idx = np.arange(0, len(dendro['ivl']))
ax2.imshow(corr[ dendro['leaves'], :] [:, dendro['leaves']])
ax2.set_xticks(dendro_idx)
ax2.set_yticks(dendro_idx)
ax2.set_xticklabels(dendro[ 'ivl'], rotation= 'vertical')
ax2.set_yticklabels(dendro[ 'ivl'])
fig.tight_layout()
plt.show()
sns.heatmap(temp_df.corr(), cmap='YlGnBu', fmt='.3f')
mask = np.zeros_like(temp_df.corr(), dtype=np.bool)
mask[np.tril_indices_from(mask)] = True
sns.heatmap(temp_df.corr(),vmin=0, vmax=0.5, mask=mask, fmt='.3f')
fig, ax = plt.subplots(1, 3, sharex='col', sharey='row', figsize=(15,5))
sns.heatmap(temp_df.corr(method='pearson'), ax=ax[0],vmin=0, vmax=0.8, fmt='.3f')
sns.heatmap(temp_df.corr(method='kendall'), ax=ax[1], cmap="Blues", fmt='.3f')
sns.heatmap(temp_df.corr(method='spearman'), ax=ax[2], cmap="YlGnBu", fmt='.3f')
fig.suptitle('Корреляционные матрицы, построенные различными методами')
ax[0].title.set_text('Pearson')
ax[1].title.set_text('Kendall')
ax[2].title.set_text('Spearman')